package cn.gjxblog.core.authentication.mobile;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * @author gjx
 * @version v1.0
 * @Description
 * @date 2019/1/17 14:12
 */
public class MobileAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        MobileAuthenticaionToken mobileAuthenticaionToken = (MobileAuthenticaionToken)authentication;
        UserDetails userDetails = userDetailsService.loadUserByUsername((String) mobileAuthenticaionToken.getPrincipal());
        if(userDetails == null){
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }
        MobileAuthenticaionToken newAuthentication = new MobileAuthenticaionToken(userDetails.getUsername(),userDetails.getAuthorities());

        newAuthentication.setDetails(mobileAuthenticaionToken.getDetails());
        return newAuthentication;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return MobileAuthenticaionToken.class.isAssignableFrom(aClass);
    }

    public UserDetailsService getUserDetailsService() {
        return userDetailsService;
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
}
